python modulo

您所在的位置:网站首页 room division是什么意思啊 python modulo

python modulo

2024-07-16 15:24| 来源: 网络整理| 查看: 265

python modulo

When you see the % symbol, you may think "percent". But in Python, as well as most other programming languages, it means something different.

当您看到%符号时,您可能会认为是“百分比”。 但是在Python以及大多数其他编程语言中,它的含义有所不同。

The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem.

Python中的%符号称为“模运算符”。 它返回左操作数除以右操作数的余数。 它用于获得除法问题的其余部分。

The modulo operator is considered an arithmetic operation, along with +, -, /, *, **, //.

模运算符与+ , - , / , * , **和//一起被视为算术运算。

The basic syntax is:

基本语法为:

a % b

In the previous example a is divided by b, and the remainder is returned. Let's see an example with numbers.

在前面的示例中, a除以b ,然后返回余数。 让我们看一个带有数字的例子。

7 % 2

The result of the previous example is one. Two goes into seven three times and there is one left over.

上一个示例的结果为one 。 2次进入7次三下,剩下一个 。

The diagram below shows a visual representation of 7 / 2 and 7 % 2 (The "R" stands for "remainder"). The single logo on the right side (with the green arrow pointing at it) is the remainder from the division problem. It is also the answer to 7 % 2.

下面示出了图的视觉表示7 / 2和7 % 2 (其中“R”代表“余数”)。 右侧的单个徽标(带有绿色箭头指向其上)是划分问题的其余部分。 这也是7 % 2的答案。

Here is another example:

这是另一个示例:

3 % 4

This will result in three. Four does not go into three any times so the original three is still left over. The diagram below shows what is happening. Remember, the modulo operator returns the remainder after performing division. The remainder is three.

这将导致三个 。 四不进入三位中的任何时间使原来的三仍遗留下来的。 下图显示了正在发生的事情。 请记住,取模运算符在执行除法运算后会返回余数。 其余为三个。

使用模运算符的示例 (Example using the Modulo Operator)

One common use for the Modulo Operator is to find even or odd numbers. The code below uses the modulo operator to print all odd numbers between 0 and 10.

模运算符的一种常见用法是查找偶数或奇数。 下面的代码使用模运算符打印0到10之间的所有奇数。

for number in range(1, 10): if(number % 2 != 0): print(number)

Result:

结果:

1 3 5 7 9

翻译自: https://www.freecodecamp.org/news/the-python-modulo-operator-what-does-the-symbol-mean-in-python-solved/

python modulo



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3